package org.mybatis.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.model.ResultDo;
import org.mybatis.model.User;
import org.mybatis.service.UserService;
import org.mybatis.util.ConfigApplication;

import com.github.pagehelper.PageInfo;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class IndexAction
 */
@WebServlet("/index") public class IndexAction extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IndexAction() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置请求以及响应的内容类型以及编码方式
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        
        String pageNo = request.getParameter("pageNo") == null ? "0" : request.getParameter("pageNo");
        String pageNum = request.getParameter("pageNum") == null ? "0" : request.getParameter("pageNum");
        
        SqlSessionFactory sqlSessionFactory = ConfigApplication.getInstance().sessionFactory();
        UserService.getInstance().initSession(sqlSessionFactory);
        PageInfo<User> pageInfo = UserService.getInstance().searchUser(Integer.parseInt(pageNo),
                Integer.parseInt(pageNum));
        
        ResultDo<Object> resultDo = new ResultDo<>();
        if (pageInfo != null){
            resultDo.code(200);
            resultDo.msg("查询成功！");
        }
        resultDo.data(pageInfo.getList());
        resultDo.count(pageInfo.getTotal());
        
        JSONObject json = JSONObject.fromObject(resultDo);
        PrintWriter out = response.getWriter();
        String str = json.toString();
        out.write(str);
    }
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
    
}
